<template>
  <div class="orders-container">
    <div class="filter-container">
    
      <el-input
        v-model="listQuery.orderNo"
        placeholder="订单号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.status" placeholder="订单状态" clearable class="filter-item" style="width: 150px">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
        class="filter-item"
        style="width: 300px"
      />

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      
      <el-button class="filter-item" type="success" icon="el-icon-download" @click="handleExport">
        导出
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="订单号" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.orderNo }}</span>
        </template>
      </el-table-column>

      <el-table-column label="客户名称" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.user ? scope.row.user.username : '未知用户' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="送水员" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.deliveryman">{{ scope.row.deliveryman.realName }}</span>
          <span v-else-if="scope.row.status === 4">-- (已取消)</span>
          <span v-else-if="scope.row.status === 0">待分配</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>

      <el-table-column label="订单金额" width="120" align="center">
        <template slot-scope="scope">
          <span>¥{{ scope.row.totalAmount }}</span>
        </template>
      </el-table-column>

      <el-table-column label="订单状态" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{ scope.row.statusName || (scope.row.status | statusLabelFilter) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="收货地址" min-width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系电话" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleDetail(scope.row)"
          >
            详情
          </el-button>
          <el-dropdown split-button type="warning" size="mini" @command="handleStatusCommand($event, scope.row)">
            修改状态
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="0" :disabled="scope.row.status === 0">待接单</el-dropdown-item>
              <el-dropdown-item :command="1" :disabled="scope.row.status === 1">已接单</el-dropdown-item>
              <el-dropdown-item :command="2" :disabled="scope.row.status === 2">配送中</el-dropdown-item>
              <el-dropdown-item :command="3" :disabled="scope.row.status === 3">已完成</el-dropdown-item>
              <el-dropdown-item :command="4" :disabled="scope.row.status === 4">已取消</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="700px">
      <div v-if="detailOrder" class="order-detail">
        <div class="order-info">
          <div class="info-item">
            <span class="label">订单号：</span>
            <span>{{ detailOrder.orderNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">客户名称：</span>
            <span>{{ detailOrder.user ? detailOrder.user.username : '未知用户' }}</span>
          </div>
          <div class="info-item">
            <span class="label">送水员：</span>
            <span v-if="detailOrder.deliveryman">{{ detailOrder.deliveryman.realName }}</span>
            <span v-else-if="detailOrder.status === 4">-- (已取消)</span>
            <span v-else-if="detailOrder.status === 0">待分配</span>
            <span v-else>未知</span>
          </div>
          <div class="info-item">
            <span class="label">订单状态：</span>
            <el-tag :type="detailOrder.status | statusFilter">{{ detailOrder.statusName || (detailOrder.status | statusLabelFilter) }}</el-tag>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span>{{ detailOrder.createTime }}</span>
          </div>
          <div class="info-item">
            <span class="label">收货地址：</span>
            <span>{{ detailOrder.address }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话：</span>
            <span>{{ detailOrder.phone }}</span>
          </div>
          <div class="info-item" v-if="detailOrder.remark">
            <span class="label">备注：</span>
            <span>{{ detailOrder.remark }}</span>
          </div>
        </div>

        <el-divider content-position="center">商品信息</el-divider>

        <el-table :data="detailOrder.orderItems || []" border style="width: 100%">
          <el-table-column label="商品图片" width="100" align="center">
            <template slot-scope="scope">
              <img v-if="scope.row.productImage" :src="'http://localhost:8080/api' + scope.row.productImage" alt="商品图片" style="height: 50px;">
              <span v-else>无图片</span>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" min-width="150" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.productName }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="品牌" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.brandName || '未知品牌' }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="单价" width="80" align="center">
            <template slot-scope="scope">
              <span>¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="80" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.quantity }}</span>
            </template>
          </el-table-column>
          <el-table-column label="小计" width="100" align="center">
            <template slot-scope="scope">
              <span>¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <div class="order-total">
          <span>订单总价：</span>
          <span class="price">¥{{ detailOrder.totalAmount }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, getOrderDetail, exportOrders, updateOrderStatus, deleteOrder, cancelOrder, acceptOrder, deliverOrder, completeOrder } from '@/api/order'
import { saveAs } from 'file-saver'

export default {
  name: 'Orders',
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'warning',  // 待接单
        1: 'primary',  // 已接单
        2: 'info',     // 配送中
        3: 'success',  // 已完成
        4: 'danger'    // 已取消
      }
      return statusMap[status]
    },
    statusLabelFilter(status) {
      const statusMap = {
        0: '待接单',
        1: '已接单',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        orderNo: undefined,
        status: undefined,
        startDate: undefined,
        endDate: undefined
      },
      dateRange: [],
      statusOptions: [
        { label: '待接单', value: 0 },
        { label: '已接单', value: 1 },
        { label: '配送中', value: 2 },
        { label: '已完成', value: 3 },
        { label: '已取消', value: 4 }
      ],
      detailDialogVisible: false,
      detailOrder: null
    }
  },
  watch: {
    dateRange(val) {
      // 日期范围暂不处理，后端不支持日期搜索
      console.log('日期范围:', val)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      // 转换查询参数
      const queryParams = {
        current: this.listQuery.page,
        size: this.listQuery.limit,
        keyword: this.listQuery.orderNo, // 使用orderNo作为关键字搜索
        status: this.listQuery.status !== undefined && this.listQuery.status !== '' ? Number(this.listQuery.status) : undefined
      }
      
      // 移除undefined的参数
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === undefined) {
          delete queryParams[key];
        }
      });
      
      console.log('查询参数:', queryParams)
      
      getOrderList(queryParams).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      }).catch(error => {
        console.error('获取订单列表失败:', error)
        this.listLoading = false
        this.$message.error('获取订单列表失败')
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleDetail(row) {
      this.detailDialogVisible = true
      
      // 获取详细订单信息
      getOrderDetail(row.id).then(response => {
        this.detailOrder = response.data
      }).catch(error => {
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败')
        // 如果获取详情失败，使用列表中的简要信息
        this.detailOrder = row
      })
    },
    // 处理状态变更命令
    handleStatusCommand(command, row) {
      const statusText = this.statusOptions.find(item => item.value === command).label
      
      this.$confirm(`确认将订单"${row.orderNo}"的状态修改为"${statusText}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 根据状态选择对应的API调用
        let apiCall
        
        switch(parseInt(command)) {
          case 0: // 待接单
            apiCall = updateOrderStatus(row.id, 0)
            break
          case 1: // 已接单
            apiCall = acceptOrder(row.id)
            break
          case 2: // 配送中
            apiCall = deliverOrder(row.id)
            break
          case 3: // 已完成
            apiCall = completeOrder(row.id)
            break
          case 4: // 已取消
            apiCall = cancelOrder(row.id)
            break
          default:
            apiCall = updateOrderStatus(row.id, command)
        }
        
        apiCall.then(() => {
          this.$message({
            message: '订单状态修改成功',
            type: 'success'
          })
          this.getList() // 刷新列表
        }).catch(error => {
          console.error('订单状态修改失败:', error)
          this.$message.error(`订单状态修改失败: ${error.message || '未知错误'}`)
        })
      }).catch(() => {})
    },
    // 处理删除订单
    handleDelete(row) {
      this.$confirm(`确认删除订单"${row.orderNo}"吗? 此操作不可逆!`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        deleteOrder(row.id).then(() => {
          this.$message({
            message: '订单删除成功',
            type: 'success'
          })
          this.getList() // 刷新列表
        }).catch(error => {
          console.error('订单删除失败:', error)
          this.$message.error(`订单删除失败: ${error.message || '未知错误'}`)
        })
      }).catch(() => {})
    },
    handleExport() {
      this.$confirm('确认导出订单数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        
        // 创建导出参数，不包含分页参数
        const exportParams = {
          keyword: this.listQuery.orderNo || undefined,
          status: this.listQuery.status !== undefined && this.listQuery.status !== '' ? Number(this.listQuery.status) : undefined
        }
        
        // 移除undefined的参数
        Object.keys(exportParams).forEach(key => {
          if (exportParams[key] === undefined) {
            delete exportParams[key];
        }
        });
        
        exportOrders(exportParams).then(response => {
          this.listLoading = false
          
          // 使用file-saver保存文件
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
          const fileName = `订单数据_${new Date().toLocaleDateString()}.xlsx`
          saveAs(blob, fileName)
          
          this.$message({
            message: '导出成功',
            type: 'success',
            duration: 2000
          })
        }).catch(error => {
          this.listLoading = false
          console.error('导出订单失败:', error)
          this.$message.error('导出订单失败')
        })
      }).catch(() => {})
    }
  },
  beforeRouteEnter(to, from, next) {
    const userRole = localStorage.getItem('userRole')
    if ((userRole || '').toLowerCase() !== 'admin') {
      next('/404')
    } else {
      next()
    }
  }
}
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.order-detail {
  padding: 10px;
}

.order-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  font-size: 14px;
}

.label {
  font-weight: bold;
  margin-right: 10px;
}

.order-total {
  margin-top: 20px;
  text-align: right;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 20px;
}

/* 操作按钮间距 */
.el-dropdown {
  margin: 0 5px;
}
</style> 